;(function($, window, document) {
    //岗位名字
    var JQ_postName=$('#JQ_post_name')
    // 弹出新建
    var JQ_dept_tbody = $('#JQ_dept_tbody');

    //返回数据
    var filter = {
        getQueryList: function (data) {
            var data = {};
            // 查询参数
            data.name = function () {
                var v = JQ_postName.val();
                if (v) {
                    return v;
                }
                return '';
            }();
            data.companyId = function() {
                var v = $JQ_upcompany_name.val();
                if (v) {
                    return convertVal(v);
                }
                return '';
            }();
            data.deptId = function() {
                var v = $JQ_unpost_name.val();
                if (v) {
                    return convertVal(v);
                }
                return '';
            }();
            return data;
        },
        // 岗位 ID 数组
        getPostIds: function(){
            var arr = [];
            var $chks = $post_table.find('i.zy-checkbox');
            if($chks.length > 0){
                $chks.each(function(){
                    var $this = $(this);
                    if($this.hasClass('active')){
                        arr.push({name:'idList',value:$this.attr('data-id')});
                    }
                });
            }
            return arr;
        },
    };

    var $JQ_upcompany_name; //上级公司下拉框
    DyyBase.ajax(sysApi.url_settings_company_search_list(), {state : 0}, function(dataset) {
        var data = dataset.result;
        var arr = [];
        arr.push({id : -1, text : '请选择上级公司'});
        for(var i = 0; i< data.length; i++) {
            arr.push({id : data[i]['id'], text : data[i]['shortName']});
        }
        $JQ_upcompany_name=$('#JQ_upcompany_name').select3({
            search: false,
            allowClear: false,
            data : arr
        });
        $JQ_upcompany_name.fit(-1);
    },{async : false});

     //上级部门下拉框
    var $JQ_unpost_name = $('#JQ_updept_name').select3({
        search: false,
        allowClear: false,
        data : [{id : -1 , text : '请选择上级部门'}]
    });
    $JQ_unpost_name.fit(-1);

    $JQ_upcompany_name.element.on('select', function(e, v) {
        var id = v || $JQ_upcompany_name.val();
        id = convertVal(id);
        if(id) {
            DyyBase.ajax(sysApi.url_settings_dept_search_list(), {state : 0, companyId : id}, function(dataset) {
                var data = dataset.result;
                var arr = [];
                arr.push({id : -1, text : '请选择上级部门'});
                for(var i = 0; i< data.length; i++) {
                    arr.push({id : data[i]['id'], text : data[i]['shortName']});
                }
                $JQ_unpost_name.asset(arr);
                $JQ_unpost_name.fit(-1);
            },{async : false});
        } else {
            $JQ_unpost_name.asset([{id : -1, text : '请选择上级部门'}]);
        }
    });

    var $post_table = $('#JQ_datatable_post').checkbox3();
    //加载表格
    var DTPOST;

    DTPOST = $post_table.DataTable({
        'language': {
            'paginate': {
                'next': '下一页',
                'previous': '上一页'
            },
            'info': '本次检索共 _TOTAL_ 条，每页显示 10 条，共 _PAGES_ 页',
            'zeroRecords': DyyBase.table_empty(),
            'infoEmpty': ''
        },
        'autoWidth': false,
        'order': [],
        'serverSide': true,
        'pageLength': false,
        'paging':false,
        'ordering': false,
        'processing': false,
        'searching': false,
        'lengthChange': false,
        'info':false,
        'ajax': function (data, callback) {
            var param = filter.getQueryList(data);
            DyyBase.ajax(sysApi.url_settings_post_search_list(), param, function  (dataset) {
                var returnData = {};
                returnData.draw = data.draw;
                returnData.data = DyyBase.clearNull(dataset.result);
                callback(returnData);
            });
        },
        'columns': [
            {
                data: 'id', render: function (data) {
                return '<i class="zy-checkbox" data-id="' + data + '" title="选中"></i>';
            }
            },
            {
                data: 'shortName', render: function (data) {
                return '<span title="' + data + '">' + data + '</span>';
            }
            },
            {
                data: 'deptIdName', render: function (data) {
                return '<span title="' + data + '">' + data + '</span>';
            }
            },
            {
                data: 'companyIdName', render: function (data) {
                return '<span title="' + data + '">' + data + '</span>';
            }
            },
            {
                data: 'state', render: function (data,type,row) {
                if(data == '0'){
                    return '<i data-id="'+row.id+'" data-state="'+data+'" class="zy-switch-sys"></i>';
                }else{
                    return '<i data-id="'+row.id+'" data-state="'+data+'" class="zy-switch-sys off"></i>';
                }
            }
            },
            {
                data: 'id', render: function (data, type, row, meta) {
                return '<i data-row="'+ meta.row + '" data-id="'+data+'" class="zy-record-add-icon" title="编辑"></i>';
            }
            },
            {
                data: 'id', className : 't-l', render: function (data) {
                return '<i data-id="'+data+'" class="zy-list-icon-delete" title="删除"></i>';
            }
            }
        ]
    });
    // 查询
    $('#JQ_search_dept').click(function () {
        if(DTPOST){
            DTPOST.draw();
        }
    });

    // 岗位管理列表 - 开/关
    $post_table.on('click','i.zy-switch-sys',function(event){
        var $this = $(this);
        var id = $this.attr('data-id'), state = $this.attr('data-state');
        state = state == '0' ? '1' : '0';

        DyyBase.ajax(sysApi.url_settings_post_updateState(),{id:id,state:state},function(dataset){
            if(dataset.bool){
                $this.toggleClass('off');
                $this.attr('data-state',state);
            }
        });
        event.stopPropagation();
        return false;
    });
    // 岗位管理列表 - 删除
    $post_table.on('click','i.zy-list-icon-delete',function(event){
        var $this = $(this);
        var id = $this.attr('data-id');
        $this.MSG({
            type: 'confirm',
            height: 230,
            content: '您确认要删除此岗位?',
            yesBtnTxt: '确认',
            yesBtnAct: function(){
                DyyBase.ajax(sysApi.url_settings_post_del(),{idList:id},function(dataset){
                    if(dataset.bool){
                        $this.MSG({
                            type: 'success',
                            content: dataset.result,
                            yesBtnAct: function(){
                                DyyBase.pageReload();
                            }
                        });
                    }
                });
            }
        });
        event.stopPropagation();
        return false;
    });
    // 岗位管理列表 - 批量删除
    $('#JQ_dept_delete').click(function(){
        var $this = $(this);
        var param = filter.getPostIds();
        var len = param.length;
        if(len){
            $this.MSG({
                type: 'confirm',
                height: 230,
                content: '您确认要删除此选中的岗位?',
                yesBtnTxt: '确认',
                yesBtnAct: function(){
                    DyyBase.ajax(sysApi.url_settings_post_del(),param,function(dataset){
                        if(dataset.bool){
                            $this.MSG({
                                type: 'success',
                                content: '已选择' + len +"条数据，成功删除" + dataset.message +"条数据",
                                yesBtnAct: function(){
                                    DyyBase.pageReload();
                                }
                            });
                        }
                    });
                }
            });
        }else{
            $this.MSG({
                content: '请选择您要删除的岗位!'
            });
        }
    });

    //编辑岗位信息
    $post_table.on('click','i.zy-record-add-icon', function(event) {
        var $this = $(this);
        var data = DTPOST.row($this.attr('data-row')).data();
        popup($this, data, "编辑岗位信息");
        event.stopPropagation();
        return false;
    });

    //弹出层
    var wind;
    var JQ_tk_post_name;//弹框部门名称
    var JQ_tk_company_select; //上级公司下拉框
    var JQ_tk_dept_select; //上级部门下拉框
    var popup = function(obj, data, title) {
        JQ_tk_post_name= $('#JQ_tk_post_name');//弹框部门名称
        DyyBase.ajax(sysApi.url_settings_company_search_list(), {state : 0}, function(dataset) {
            var data = dataset.result;
            var arr = [];
            arr.push({id : -1, text : '请选择上级公司'});
            for(var i = 0; i< data.length; i++) {
                arr.push({id : data[i]['id'], text : data[i]['shortName']});
            }
            JQ_tk_company_select=$('#JQ_tk_company_name').select3({
                search: false,
                allowClear: false,
                data : arr
            });
            JQ_tk_company_select.fit(-1);
        },{async : false});


        JQ_tk_dept_select= $('#JQ_tk_dept').select3({
            search: false,
            allowClear: false,
            data : [{id : -1, text : '请选择上级部门'}]
        });
        JQ_tk_dept_select.fit(-1);
        JQ_tk_company_select.element.on('select', function() {
            var companyId = convertVal(JQ_tk_company_select.val());
            if(companyId) {
                DyyBase.ajax(sysApi.url_settings_dept_search_list(), {state : 0, companyId : companyId}, function(dataset) {
                    var data = dataset.result;
                    var arr = [];
                    arr.push({id : -1, text : '请选择上级部门'});
                    for(var i = 0; i< data.length; i++) {
                        arr.push({id : data[i]['id'], text : data[i]['shortName']});
                    }
                    JQ_tk_dept_select.asset(arr);
                },{async : false});
            } else {
                JQ_tk_dept_select.asset([{id : -1, text : '请选择上级部门'}]);
            }
        });


        JQ_tk_post_name.val(data.shortName);
        if(data.companyId && data.companyId !== '-' && data.companyId !== -1) {
            JQ_tk_company_select.fit(data.companyId);
            setTimeout(function() {
                JQ_tk_company_select.element.trigger('select');
            }, 100);
        } else {
            JQ_tk_company_select.fit(-1);
        }

        JQ_tk_dept_select.asset([{id : -1, text : '请选择上级部门'}]);
        if(data.deptId && data.deptId !== '-' && data.deptId !== -1) {
            setTimeout(function() {
                JQ_tk_dept_select.fit(data.deptId);
            }, 100);
        } else {
            JQ_tk_dept_select.fit(-1);
        }
        if(data.createRemark && data.createRemark !== '-') {
            $('#Jq-bz').val(data.createRemark);
        } else {
            $('#Jq-bz').val('');
        }
        if(data.id && data.id !== '-') {
            $('#postId').val(data.id);
        } else {
            $('#postId').val('');
        }
        wind = $(obj).WIND({
            width: 640,
            height: 320,
            title: title,
            actionBox: 'div.plan-box',
            closeBtn: 'i.plan-close',
            yesBtn: 'JQ_action_yes_btn',
            noBtn: '',
            yesBtnTxt: '确定',
            noBtnTxt: '',
            yesBtnAct: addOrUpdatePost
        });
    };

    //更新或者增加部门
    function addOrUpdatePost() {
        var verify = $post_form.verify();
        if(verify){
            var data = {};
            data.mode = true;
            var post_name= JQ_tk_post_name.val();
            data.shortName = post_name;
            data.createRemark = $('#Jq-bz').val();
            data.id = $('#postId').val();
            data.companyId = function() {
                var v = convertVal(JQ_tk_company_select.val());
                if(v) {
                    return v;
                } else {
                    JQ_tk_company_select.element.TIP({content: '上级公司不能为空!'});
                    data.mode = false;
                }
                return '';
            }();
            data.deptId = function() {
                var v = convertVal(JQ_tk_dept_select.val());
                if(v) {
                    return v;
                } else {
                    JQ_tk_dept_select.element.TIP({content: '上级部门不能为空!'});
                    data.mode = false;
                }
                return '';
            }();
            // 保存或者操作
            if(data.mode){
                var url;
                if(data.id) {
                    url = sysApi.url_settings_post_update();
                } else {
                    url = sysApi.url_settings_post_add();
                }
                DyyBase.ajax(url, data, function(dataset){
                    if(dataset.bool){
                        wind.clear();
                        $(this).MSG({
                            type: 'success',
                            content: dataset.result,
                            yesBtnAct : function() {
                                DyyBase.pageReload();
                            }
                        });
                    }else{
                        wind.clear();
                        $(this).MSG({
                            type: 'error',
                            content: dataset.result
                        });
                    }
                });
            }
        }
    }

    /**
     * 转换-1为空字符串
     * @param val
     * @returns {*}
     */
    function convertVal(val) {
        if(val === '-1' || val < 0) {
            return '';
        }
        return val;
    }

    //新建岗位信息
    var $post_form = $('#JQ_post_form');
    JQ_dept_tbody.on('click',function(){
        var $this = $(this);
        popup($this, {}, "新建岗位信息");
    });

})(jQuery, window, document);